/**
 * @see 办事指南界面
 */

const fileIcon = {
	excel: "https://xwx.gzzmedu.com:6899/pic/wx-x-mai/file-icon/excel.png",
	image: "https://xwx.gzzmedu.com:6899/pic/wx-x-mai/file-icon/image.png",
	pdf: "https://xwx.gzzmedu.com:6899/pic/wx-x-mai/file-icon/pdf.png",
	docx: "https://xwx.gzzmedu.com:6899/pic/wx-x-mai/file-icon/word.png",
}
const towxml = require("../../../../towxml/index")
import { timestampToTime } from "../../../../utils/util"
let headlineId = ""
let token = ""
let str
let num = 0
let timer = null
Page({
	data: {
		appMsg: {
			type: "", // 状态
			show: false, // 是否展示
		},
		details: {
			fileList: [],
		},
		article: "",
		showShare: false,
		scrollHeight: 0, // 文章总高度
		scrollTop: 0, // 滚动距离
		readingRate: 0, // 阅读率
	},
	onLoad(option) {
		headlineId = option.headlineId
		token = wx.getStorageSync("token")
		this.getWorkInfo(headlineId)
		this.clickTotal()
		this.computedRead()
	},
	// 计算阅读率
	computedRead() {},
	/**
	 * @see 点击量
	 */
	clickTotal() {
		console.log("点击量加一")
		wx.$API["home/articleClick"]({
			articleId: headlineId,
		})
		return
		const request = {}
		wx.$API["workService/clickTotal"](request).then((result) => {
			console.log(result)
		})
	},
	/**
	 *
	 * @see 解析富文本
	 */
	parsingText() {
		try {
			let result = towxml(this.data.article, "html", {
				events: {
					tap: (e) => {
						if (e.target.dataset.data && e.target.dataset.data.attr.src) {
							wx.previewImage({
								current: e.target.dataset.data.attr.src,
								urls: [e.target.dataset.data.attr.src],
								fail: (res) => {
									wx.showModal({
										title: "您的网络视乎有波动~",
										content: "",
									})
								},
							})
						}
					},
					longpress: (e) => {
						try {
							if (
								!e ||
								!e.currentTarget ||
								!e.currentTarget.dataset ||
								!e.currentTarget.dataset.data ||
								!e.currentTarget.dataset.data.child[0]
							) {
								return
							}
							wx.setClipboardData({
								data: e.currentTarget.dataset.data.child[0].text,
								success(res) {
									wx.getClipboardData({
										success: (res) => {
											console.log(res.data) // data
										},
									})
								},
								fail: (err = "") => {
									wx.showToast({
										title: "复制失败",
										icon: "none",
									})
									console.log(err)
								},
							})
						} catch (err) {
							console.log(err)
						}
					},
				},
			})
			this.setData({
				article: result,
			})
		} catch (err) {
			console.error("富文本解析出错: ", err)
			this.showToast({
				title: "内容解析错误,请刷新再试",
				icon: "none",
				duration: 2000,
			})
		}
	},
	/**
	 * @see 接口-获取头条详情
	 */
	getWorkInfo(headlineId) {
		wx.showLoading({
			title: "加载中...",
		})
		this.setData({
			appMsg: {
				headlineId,
			},
		})
		const request = { headlineId }
		wx.$API["workService/getShcoolHeadLine"](request)
			.then((result) => {
				this.setData({
					appMsg: {
						type: "loading",
						show: false,
					},
				})
				const { data } = result
				let timeText = timestampToTime(data[0].createTime)
				// 后台对图片路径做了处理,需要动态调用接口返回图片资源,首先用正则解析富文本,拿到所有的img标签,再用正则拿到所有的img标签中的src属性,再通过replace方法替换掉每一个img的src属性 115行到153行是解析富文本图片
				str = data[0].content
				var imgReg = /<img.*?(?:>|\/>)/gi
				var srcReg = /src=[\'\"]?([^\'\"]*)[\'\"]?/i
				var arr = str.match(imgReg)
				const promiseAll = []
				if (arr) {
					for (var i = 0; i < arr.length; i++) {
						var src = arr[i].match(srcReg)
						if (src[1]) {
							let request = {
								resourceUrl: src[1],
							}
							promiseAll.push(wx.$API["workService/getAuthUrl"](request))
						}
					}
				}
				new Promise((resolve, reject) => {
					Promise.all(promiseAll)
						.then((res) => {
							if (!res.length) {
								this.setData({ article: str })
								resolve()
							}
							res.forEach((result, i) => {
								let authUrl = result.data[0].authUrl
								str = str.replace(
									/(?![src="])http:\/\/tp\.gzzmedu\.com\/\w+\.(jpg|png|jpeg)(?=["])/i,
									authUrl,
								)
								if (i >= res.length - 1) {
									this.setData({ article: str })
									resolve()
								}
							})
						})
						.catch((error) => {
							reject(error)
						})
				})
					.then(() => {
						data[0].year = timeText.split(" ")[0]
						data[0].headlineEnclosureList.forEach((item) => {
							item.icon = fileIcon[item.fileType]
						})
						this.setData({
							details: data[0],
							showShare: true,
						})
						this.parsingText()
						wx.hideLoading()
						setTimeout(() => {
							// 获取文章总高度
							const query = wx.createSelectorQuery()
							query.select("#ql-editor").boundingClientRect()
							query.exec((res) => {
								console.log(res[0].height, "获取到文章总高度")
								this.setData({
									scrollHeight: res[0].height,
								})
							})
						}, 100)
					})
					.catch((error) => {
						console.error(error)
						this.setData({
							appMsg: {
								type: "err",
								show: true,
							},
						})
						wx.hideLoading()
					})
			})
			.catch((error) => {
				console.error(error)
				this.setData({
					appMsg: {
						type: "err",
						show: true,
					},
				})
				wx.hideLoading()
			})
	},
	/**
	 * @see 选择文件
	 */
	handleFile(e) {
		const item = e.currentTarget.dataset.item
		wx.showLoading({ title: "正在下载...", mask: true })
		wx.downloadFile({
			url: item.url,
			// url: 'http://192.168.7.178:7003/api/office-service-ms/loadNoticeFile?schoolCode=4000011111&fileName=zwcjd.pdf',
			// url: 'http://192.168.7.178:7003/api/office-service-ms/pic/4000011111/bg2.jpg',
			header: {
				"X-Authorization": token,
			},
			success: (res) => {
				wx.hideLoading()
				const { statusCode, tempFilePath } = res
				if (statusCode === 200) {
					if (item.type === "image") {
						wx.previewImage({ urls: [tempFilePath] })
					} else {
						wx.openDocument({
							filePath: tempFilePath,
							fileType: item.fileType,
							fail: () => {
								wx.showToast({
									title: "打开失败!",
									icon: "none",
									duration: 2000,
								})
							},
						})
					}
				}
			},
			fail: (err) => {
				wx.hideLoading()
				wx.showToast({
					title: "下载失败!",
					icon: "none",
					duration: 2000,
				})
				alert(err)
			},
		})
	},
	/**
	 * @see 点击刷新界面
	 */
	clickMsgButton() {
		this.getWorkInfo(headlineId)
	},
	// 保存阅读率
	saveRead() {
		wx.$API["home/articleProgress"]({
			articleId: headlineId,
			progressRate: this.data.readingRate >= 1 ? 1 : this.data.readingRate,
		})
			.then(() => {
				console.log("保存阅读文章进度完成")
			})
			.catch((error) => {
				console.log("保存阅读文章进度失败")
			})
	},
	onPageScroll: function (e) {
		// 更新滚动距离
		this.setData({
			scrollTop: e.scrollTop,
		})
		// 计算阅读率
		const readingRate = (
			(e.scrollTop + wx.getSystemInfoSync().windowHeight) /
			this.data.scrollHeight
		).toFixed(2)
		console.log(readingRate, "计算出来的yuedulv")
		clearTimeout(timer)
		timer = 0
		timer = setTimeout(() => {
			this.saveRead()
		}, 500)
		this.setData({
			readingRate: readingRate,
		})
	},
})
